package com.sense.kukoo.biz_explore.view

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_explore.R
import com.sense.kukoo.biz_explore.adapter.ExploreContentAdapter
import com.sense.kukoo.biz_explore.databinding.BizExploreFragmentContentBinding
import com.sense.kukoo.biz_explore.vm.ACTION_FINISH_LOAD_MORE
import com.sense.kukoo.biz_explore.vm.ContentViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.bean.BookBean
import com.sense.kukoo.common.repo.bean.BookItemBean
import com.sense.kukoo.common.repo.bean.ExploreContentBean
import com.sense.kukoo.common.repo.bean.IndexBean
import com.sense.kukoo.common.wiget.state.EmptyListState
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.sense.kukoo.lib_logger.LoggerManager
import com.zy.multistatepage.state.SuccessState

private const val ARG_TAB = "tab"

class ContentFragment : BaseMvvmFragment<ContentViewModel, BizExploreFragmentContentBinding>() {

    private val TAG: String = javaClass.simpleName
    private lateinit var navMenu: IndexBean.NavMenu
    private lateinit var mAdapter:ExploreContentAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            navMenu = it.getParcelable(ARG_TAB)!!
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(tab: IndexBean.NavMenu) =
            ContentFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ARG_TAB, tab)
                }
            }
    }

    override fun getLayout(): Int = R.layout.biz_explore_fragment_content

    override fun getViewModelClass(): Class<ContentViewModel> = ContentViewModel::class.java

    //根据code来创建ViewModel，避免重复
    override fun createViewModel(clazz: Class<ContentViewModel>): ContentViewModel {
        return ViewModelProvider(requireActivity()).get(navMenu.code, clazz)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        mViewModel.exploreContentData.observe(viewLifecycleOwner){
            //
            if(it.size==0){
                multiState.show<EmptyListState>()
            }else{
                multiState.show<SuccessState>()
                //
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
                mAdapter.list = it
                mAdapter.notifyDataSetChanged()
            }
        }
        mViewModel.enableLoadMore.observe(viewLifecycleOwner){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
    }

    override fun initView() {
        LoggerManager.d(TAG, "navMenu=${navMenu.title}")

        mAdapter = ExploreContentAdapter(mutableListOf(), mEventListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.getRecommendData()
            mBinding.refreshLayout.setNoMoreData(false)
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.getMoreData()
        }
    }

    override fun singleLazyLoad() {
        mViewModel.mCode = navMenu.code
        mBinding.refreshLayout.autoRefresh()
    }

    override fun onShowNetworkError() {
        ToastUtils.showToast(getString(com.sense.kukoo.common_i18n.R.string.search_no_net_toast))
        multiState.show<NetworkErrorState> {
            it.onRetry {
                mViewModel.retryNetwork()
            }
        }
    }

    //
    private val mEventListener = object: ExploreContentAdapter.ExploreContentEventListener {

        override fun onClickSeeAll(bean: ExploreContentBean, code: String) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_EXPLORE_MODULE_MUSIC_COLLECTION_ACTIVITY)
                .withParcelable(ARouterUrl.KEY_EXPLORE_CONTENT, bean)
                .navigation()
        }

        override fun onClickBook(bean: ExploreContentBean, book: BookBean) {
            when (book.type) {
                BookBean.TYPE_SHORT_AUDIO -> {
                    //特殊处理：点击短音频单集内容的任意区域，直接播放该内容
                    if(book.isChapter==1){
                        playMusic(book)
                    }else{
                        ARouter.getInstance()
                            .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                            .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+book.id)
                            .navigation()
                    }
                }
                BookBean.TYPE_PODCAST -> {
                    //博客
                    if(book.isChapter==1){
                        //-》 博客单集详情页
                        val bookItemBean: BookItemBean = book.bookItems!!.get(0)
                        /*val data = LocalMediaListItemBean()
                        data.book = bookItemBean
                        data.mCoverUrl = book.coverUrl
                        data.name = book.name
                        data.isSubscription = book.isSubscription
                        data.chapterTotal = book.chapterTotal
                        data.isChapter = book.isChapter
                        data.type = book.type ?: 0
                        //
                        ARouter.getInstance()
                            .build(ARouterUrl.ROUTE_MEDIA_MODULE_PODCAST_DETAIL_ACTIVITY)
                            .withInt(ARouterUrl.KEY_FROM, 1)
                            .withParcelable(ARouterUrl.KEY_LOCAL_MEDIA_LIST_ITEMBEAN, data)
                            .navigation()*/
                    }else{
                        //-》 非单集
                        ARouter.getInstance()
                            .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                            .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+book.id)
                            .navigation()
                    }
                }
                else -> {
                    //进入该内容的详情页
                    ARouter.getInstance()
                        .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                        .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+book.id)
                        .navigation()
                }
            }

        }

        override fun onClickBookPlay(bean: ExploreContentBean, book: BookBean) {
            playMusic(book)
        }
    }

    private fun playMusic(book: BookBean){
        /*val bookItemBean: BookItemBean = book.bookItems!!.get(0)
        val data = LocalMediaListItemBean()
        data.book = bookItemBean
        data.mCoverUrl = book.coverUrl
        data.name = book.name
        data.isSubscription = book.isSubscription
        data.chapterTotal = book.chapterTotal
        data.isChapter = book.isChapter
        data.type = book.type ?: 0
        Kukoo.input.play(data)*/
    }

    override fun initParam() {}

    override fun responseVM(action: Int) {
        LoggerManager.e(TAG, "responseVM action=${action}")
        when (action) {
            ACTION_FINISH_LOAD_MORE -> {
                mBinding.refreshLayout.finishLoadMore()
            }
            else -> {}
        }
    }

}